<?php

namespace App\Helpers;

use Psr\Http\Message\ServerRequestInterface as Request;

class RequestHelper
{
    public static function isAjax(): bool
    {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            return true;
        } else {
            return false;
        }
    }

    public static function getClientIpAddress(Request $request): string
    {
        $server = $request->getServerParams();
        $ip = '';
        if (isset($server['X-Forwarded-For'])) {
            $ip = $server['X-Forwarded-For'];
        } elseif (isset($server['Proxy-Client-IP'])) {
            $ip = $server['Proxy-Client-IP'];
        } elseif (isset($server['HTTP_X_FORWARDED_FOR'])) {
            $ip = $server['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($server['HTTP_X_FORWARDED'])) {
            $ip = $server['HTTP_X_FORWARDED'];
        } elseif (isset($server['HTTP_CLIENT_IP'])) {
            $ip = $server['HTTP_CLIENT_IP'];
        } elseif (isset($server['HTTP_FORWARDED_FOR'])) {
            $ip = $server['HTTP_FORWARDED_FOR'];
        } elseif (isset($server['HTTP_FORWARDED'])) {
            $ip = $server['HTTP_FORWARDED'];
        } elseif (isset($server['REMOTE_ADDR'])) {
            $ip = $server['REMOTE_ADDR'];
        }
        if ($ip == '') {
            $ip = '0.0.0.0';
        }
        return $ip;
    }
}
